package com.dnzx.auth;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dnzx.framework.result.domain.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.dnzx.model.system.UserBO;
import com.dnzx.service.IUserService;
import com.dnzx.util.JwtTokenUtil;

public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private UserDetailsService myUserDetailsService;

    @Value("${jwt.header}")
    private String tokenHeader;
    
    private String tokenHead = "Bearer ";

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private IUserService userService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
//    	chain.doFilter(request, response);
//    	return;
    	String servletPath = request.getServletPath();
        String method = request.getMethod();
        Result result = new Result();
        if ("OPTIONS".equals(method) 
        		|| servletPath.contains("/auth/")
        		|| servletPath.contains("/web/")
        		|| servletPath.contains("/attachment/")
        		|| servletPath.contains("/api/version/")
        		|| servletPath.contains("swagger") || servletPath.contains("configuration")
        		|| servletPath.contains("v2/api-docs")
        		) {//登陆和swagger不处理
            chain.doFilter(request, response);
            return;
        }
        String authHeader = request.getHeader(this.tokenHeader);
        if (authHeader != null && !"".equals(authHeader)) {
            final String authToken = authHeader;
            String username = jwtTokenUtil.getUsernameFromToken(authToken);
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                UserDetails userDetails = this.myUserDetailsService.loadUserByUsername(username);
                if (jwtTokenUtil.validateToken(authToken, userDetails)) {
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                    try {
                        chain.doFilter(request, response);
                    } catch (Exception e) {
                        response.setContentType("application/json;charset=UTF-8");
                        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                        result.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                        result.setMsg("服务异常");
                        JSON.writeJSONStringTo(result, response.getWriter(), SerializerFeature.WriteMapNullValue);
                    }
                } else {
                    response.setContentType("application/json;charset=UTF-8");
                    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    result.setCode(HttpServletResponse.SC_UNAUTHORIZED);
                    result.setMsg("未授权");
                    JSON.writeJSONStringTo(result, response.getWriter(), SerializerFeature.WriteMapNullValue);
                }
            } else {
                response.setContentType("application/json;charset=UTF-8");
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                result.setCode(HttpServletResponse.SC_UNAUTHORIZED);
                result.setMsg("未授权");
                JSON.writeJSONStringTo(result, response.getWriter(), SerializerFeature.WriteMapNullValue);
            }
        } else {
            //(token不能为空，或者格式错误)
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            result.setCode(HttpServletResponse.SC_UNAUTHORIZED);
            result.setMsg("未授权");
            JSON.writeJSONStringTo(result, response.getWriter(), SerializerFeature.WriteMapNullValue);
        }
    }

}
